package com.carryon.modules.sj.execute;

import java.lang.reflect.Method;
import java.util.Map;

import com.carryon.modules.sj.Execute;
import com.carryon.modules.sj.SJ;
import com.carryon.modules.sj.exception.InternalServerException;

/**
 * @author Helin
 * @mail hl_0074@sina.com
 * @date 2011-9-28
 * 
 */
public class StaticMethodExcecute implements Execute {

	private Class<? extends Object> clazz;
	private String method;

	public StaticMethodExcecute(Class<? extends Object> clazz, String method) {

		this.clazz = clazz;
		this.method = method;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void execute(SJ sj) throws Exception {

		Method invoke = null;
		try {
			invoke = this.clazz.getMethod(this.method, Map.class);
		} catch (Exception e) {
			throw new InternalServerException("method not found: Map<String,Object> " + this.clazz.getCanonicalName() + "." + this.method
					+ "(Map<String,Object> request)", e);
		}

		if (!Map.class.isAssignableFrom(invoke.getReturnType())) {
			throw new InternalServerException("method not found: Map<String,Object> " + this.clazz.getCanonicalName() + "." + this.method
					+ "(Map<String,Object> request)");
		}

		try {
			invoke.setAccessible(true);
			Map<String, Object> resp = (Map<String, Object>) invoke.invoke(this.clazz, sj.getRequest());
			sj.getResponse().putAll(resp);
		} catch (Exception e) {
			throw new Exception(e.getCause().getMessage(),e);
		}
	}

}
